package com.loe.ui.quickjs

import android.webkit.JavascriptInterface
import com.loe.http.Link
import com.loe.ui.registerFunReturn
import com.quickjs.*

/** 网络请求 */
fun JSContext.initLink() = registerClass({ thisObj, args ->

    val link = Link(args.getString(0))

    thisObj.appendJavascriptInterface(object
    {
        @JavascriptInterface
        fun header(key: String, value: String): JSObject
        {
            link.header(key, value)
            return thisObj
        }

        @JavascriptInterface
        fun isJson(): JSObject
        {
            link.isJson()
            return thisObj
        }

        @JavascriptInterface
        fun error(callback: JSFunction): JSObject
        {
            link.error()
            {
                callback.call(thisObj, JSArray(context).push(it))
            }
            return thisObj
        }

        @JavascriptInterface
        fun okString(callback: JSFunction): JSObject
        {
            link.okString()
            {
                callback.call(thisObj, JSArray(context).push(it))
            }
            return thisObj
        }

        @JavascriptInterface
        fun get(): JSObject
        {
            link.get()
            return thisObj
        }

        @JavascriptInterface
        fun post(): JSObject
        {
            link.post()
            return thisObj
        }

        @JavascriptInterface
        fun end(): JSObject
        {
            link.end()
            return thisObj
        }
    })
    // param
    thisObj.registerFunReturn("param")
    {
        link.param(it.getString(0), it.get(1))
        return@registerFunReturn thisObj
    }
}, "Link")